import { View, Input } from '@tarojs/components';
import { useEffect, useState } from 'react';
import './index.scss';

interface IProps {
  value: string | undefined;
  name: string;
  placeholder?: string;
  title: string;
  onChange: (value?: string) => void;
  required?: boolean;
  bordered?: boolean;
  // children: any;
}

export default function ({
  title,
  placeholder,
  value,
  onChange = () => {},
  required,
  bordered,
}: IProps) {
  const [_value, setValue] = useState<string | undefined>(value);
  const [focus, setFocus] = useState(false);

  useEffect(() => {
    setValue(value);
  }, [value]);

  const _onChange = (val: string) => {
    setValue(val);
    onChange(val);
  };
  return (
    <View className={`input-item ${bordered ? 'bordered' : ''}`}>
      <View
        className={`input-item-name ${required ? 'red-title' : ''}`}
      >
        {title}
      </View>
      <View className="input-item-right">
        {!focus ? (
          <View className="input-value" onClick={() => setFocus(true)}>
            {_value}
          </View>
        ) : (
          <Input
            className="input-input"
            placeholder={placeholder}
            value={_value}
            focus={focus}
            onBlur={() => setFocus(false)}
            onInput={(e: any) => {
              _onChange(e.currentTarget.value);
            }}
          />
        )}
      </View>
    </View>
  );
}
